<?php
class UserToCategory
{
	
	var $tbl;
	
	
	function UserToCategory() {
	
	}
	
	
	// get array with attachments filenames
	function &_getUserDataById($record_id, $rule, $table, $fields) {
		
		list($user_id, $user_value) = $fields;
		$fields = implode(', ', $fields);
		
		$sql = "
		SELECT 
			{$fields}
		FROM 
			{$this->tbl->data_to_user_rule} d, 
			{$this->tbl->data_to_user_value} dv,
			{$table}
		WHERE 1
			AND d.title = '{$rule}'
			AND d.id = dv.rule_id
			AND dv.data_value IN ($record_id) 
			AND dv.user_value = {$user_id}";
		
		$result =& $this->db->Execute($sql) or die(db_error($sql));
		return $result->GetAssoc();
	}	
	
	
	function getAdminUserById($record_id) {
			return $this->_getUserDataById($record_id, 
		                                      'kb_category_to_admin', 
		                                      's_user u', 
											   array('u.id', 'CONCAT(u.first_name, " ", u.last_name)'));
	}
	
	
	function getRuleId($rule) {
		$sql = "SELECT id FROM {$this->tbl->data_to_user_rule} d
		WHERE d.title = '{$rule}'";
		$result =& $this->db->Execute($sql) or die(db_error($sql));
		return $result->Fields('id');
	}
	
	
	function saveAdminUserToCategory($obj, $record_id) {
		$this->_saveUserDataToCategory($obj->getAdminUser(), $record_id, 'kb_category_to_admin');
	}
	
	
	function _saveUserDataToCategory($data, $record_id, $rule) {
		
		if(!$data) { return; }
		
		require_once 'eleontev/SQL/MultiInsert.php';
		
		$rule_id = $this->getRuleId($rule);
		foreach($data as $k => $v) {
			$_data[] = array($v);
		}
		
		$ins = new MultiInsert;
		$ins->setFields('user_value', array('rule_id', 'data_value'));
		$ins->setValues($_data, array($rule_id, $record_id));
		$sql = $ins->getSql($this->tbl->data_to_user_value);
		
		//echo "<pre>"; print_r($sql); echo "</pre>";
		//exit;
		
		return $this->db->Execute($sql) or die(db_error($sql));
	}
	
	function deleteAdminUserToCategory($record_id) {
		$this->_deleteUserDataToCategory($record_id, 'kb_category_to_admin');
	}
	
	function _deleteUserDataToCategory($record_id, $rule) {
		
		$rule_id = $this->getRuleId($rule);
	
		$sql = "DELETE FROM {$this->tbl->data_to_user_value} 
		WHERE rule_id = '{$rule_id}' AND data_value = '{$record_id}'";
		//echo "<pre>"; print_r($sql); echo "</pre>";
		//exit;
		
		return $this->db->Execute($sql) or die(db_error($sql));
	}

	
	// used when wrong submit to generate list 
	function getAdminUserByIds($ids) {
		$sql = "SELECT u.id, CONCAT(u.first_name, ' ', u.last_name) 
		FROM {$this->tbl->user} u
		WHERE u.id IN ($ids)";
			
		$result =& $this->db->Execute($sql) or die(db_error($sql));
		return $result->GetAssoc();	
	}
	
	

}
?>